package org.merka.cryptochat.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.merka.cryptochat.dao.IUserManager;
import org.merka.cryptochat.entity.ChatPublicKey;
import org.merka.cryptochat.entity.ChatUser;
import org.merka.cryptochat.exception.CryptoChatException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;

public class MemoryUserManager implements IUserManager, InitializingBean
{

	private static final String FAKE_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALQBJizEHmH3h72hQvKO7pV0xqA4+dBPl/u7WQ9MtzWaHTA/kkpxc/TpMobGoZURupJanEAQOZ9iez+d810Q2jsCAwEAAQ==";

	private LinkedHashMap<String, ChatUser> users = new LinkedHashMap<String, ChatUser>();
	
	@Value("${mock.user.name.prefix}")
	private String fakeUserNamePrefix;
	
	@Value("${mock.user.count}")
	public String mockUsersCount;
	
	public LinkedHashMap<String, ChatUser> getUsers()
	{
		return users;
	}

	protected void setUsers(LinkedHashMap<String, ChatUser> users)
	{
		this.users = users;
	}
	
	public List<ChatUser> getUsersList()
	{
		ArrayList<ChatUser> list = new ArrayList<ChatUser>();
		boolean ok = list.addAll(getUsers().values());
		if(!ok)
		{
			throw new RuntimeException("Error while filling the list of ChatUsers");
		}
		return list;
	}

	@Override
	public ChatUser findChatUserByUsername(String username)
	{
		return getUsers().get(username);
	}

	@Override
	public void addChatUser(ChatUser user)
	{
		getUsers().put(user.getUsername(), user);
	}

	@Override
	public Map<String, ChatUser> getUsersMap()
	{
		return getUsers();
	}

	protected void loadAllUsers() throws CryptoChatException
	{
		int usersCount = 0;
		try
		{
			usersCount = Integer.valueOf(mockUsersCount);
		}
		catch(NumberFormatException e)
		{
			throw new CryptoChatException("Error while converting a String property into an int [value=" + mockUsersCount + "]", e);
		}
		for(int i = 0; i < usersCount; i++)
		{
			ChatPublicKey chatPublicKey = new ChatPublicKey(FAKE_KEY);
			String username = fakeUserNamePrefix + "_" + i;
			ChatUser user = new ChatUser(username, chatPublicKey);
			getUsers().put(username, user);
		}
	}
	
	@Override
	public void afterPropertiesSet() throws Exception
	{
		loadAllUsers();
	}

}
